#include "StdAfx.h"
#include "Font.h"
#include "Graphics.h"

namespace Renderer
{

	Font::Font()
	{
		font = NULL;
	}

	Font::~Font()
	{
		Free();
	}

	ID3DXFont* Font::GetFontCOM()
	{
		return font;
	}

	bool Font::Create(Graphics* graphics, ID3DXSprite * spriteBatch, char* name, long size, bool bold, bool italic)
	{
		D3DXFONT_DESC desc;

		if(graphics == NULL || name == NULL)
			return false;
		if(graphics->GetDeviceCOM() == NULL)
			return false;

		sprite = spriteBatch;
		if(sprite == NULL)
			return false;

		ZeroMemory(&desc, sizeof(D3DXFONT_DESC));

		strcpy_s(desc.FaceName,strlen(name) + 1, name);
		desc.Height = size;
		desc.Weight = (bold ? 700 : 0);
		desc.Italic = italic;
		desc.MipLevels = 1;
		desc.CharSet = DEFAULT_CHARSET;
		desc.OutputPrecision = OUT_DEFAULT_PRECIS;
		desc.Quality = DEFAULT_QUALITY;
		desc.PitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
		return SUCCEEDED(D3DXCreateFont(graphics->GetDeviceCOM(),
			size,
			size,
			(bold ? 700 : 0),
			1,
			italic,
			DEFAULT_CHARSET,
			OUT_DEFAULT_PRECIS,
			DEFAULT_QUALITY,
			DEFAULT_PITCH | FF_DONTCARE,
			name, 
			&font));
	}

	void Font::Free()
	{
		ReleaseCOM(font);
	}

	void Font::Print(char *text, long posX, long posY, long width, long height, D3DCOLOR color, DWORD format)
	{
		RECT rect;
		ZeroMemory(&rect, sizeof(RECT));
		rect.left = posX;
		rect.top = posY;

		if(width == 0)
		{
			TEXTMETRIC met;
			font->GetTextMetrics(&met);
			rect.right = met.tmMaxCharWidth * strlen(text);
		}
		else
		{
			rect.right = rect.left + width;
		}

		if(height == 0)
		{
			TEXTMETRIC met;
			font->GetTextMetrics(&met);
			rect.bottom = met.tmHeight + posY;
		}
		else
		{
			rect.bottom = rect.bottom + height;
		}

		D3DXMATRIX mat;
		D3DXMatrixIdentity(&mat);
		sprite->SetTransform(&mat);
		HR(font->DrawText(sprite, text, -1, &rect, DT_NOCLIP, color));
	}

	void Font::OnResetDevice()
	{
		HR(font->OnResetDevice());
	}

	void Font::OnLostDevice()
	{
		HR(font->OnResetDevice());
	}

}